package com.baomidou.springwind.controller;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.entity.CityOrder;
import com.baomidou.springwind.entity.Message;
import com.baomidou.springwind.entity.Project;
import com.baomidou.springwind.mapper.UserMapper;
import com.baomidou.springwind.msg.MailSender;
import com.baomidou.springwind.utils.DateUtils;
import com.baomidou.springwind.utils.ParamMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.kisso.common.encrypt.SaltEncoder;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.entity.User;
import com.baomidou.springwind.service.IRoleService;
import com.baomidou.springwind.service.IUserService;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * <p>
 * 用户管理相关操作
 * </p>
 *
 *
 * @Author Jack
 * @Date 2016/4/15 15:03
 */
@Controller
@RequestMapping("/perm/user")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private MailSender mailSender;

	@Value("${mail.recipient}")
	private String recipient;

	@Permission("2001")
	@RequestMapping("/list")
	public String list(Model model) {
		return "/user/list";
	}

	@Permission("2001")
	@RequestMapping("/examineA/list")
	public String list1(Model model) {
		return "/user/examineList";
	}

    @Permission("2001")
    @RequestMapping("/edit")
    public String edit(Model model, Long id ) {
    	if ( id != null ) {
			model.addAttribute("user", userService.selectById(id));
		}
    	model.addAttribute("roleList", roleService.selectList(null));
        return "/user/edit";
    }
    
	@ResponseBody
	@Permission("2001")
	@RequestMapping("/editUser")
	public String editUser( User user ) {
		boolean rlt = false;
		if ( user != null ) {
			user.setPassword(SaltEncoder.md5SaltEncode(user.getLoginName(), user.getPassword()));
			if ( user.getId() != null ) {
				rlt = userService.updateById(user);
			} else {
				user.setCrTime(new Date());
				user.setLastTime(user.getCrTime());
				rlt = userService.insert(user);
			}
		}
		return callbackSuccess(rlt);
	}

	@ResponseBody
	@Permission("2001")
	@RequestMapping("/getUserList")
	public String getUserList() {
		Page<User> page = getPage();
		return jsonPage(userService.selectPage(page, null));
	}

	@ResponseBody
	@Permission("2001")
	@RequestMapping("/delUser/{userId}")
	public String delUser(@PathVariable Long userId) {
        userService.deleteUser(userId);
		return Boolean.TRUE.toString();
	}

	@ResponseBody
	@Permission("2001")
	@RequestMapping("/examineA/{userId}")
	public String examineA(@PathVariable Long userId) throws Exception{
		ParamMap<String, Object> pm=new ParamMap<String, Object>();
		pm.put("id",userId);
		userMapper.updateExamineA(pm);
		User user=userService.selectById(userId);
		sentEmail(user.getName(),user.getLoginName());
		return Boolean.TRUE.toString();
	}
	public void sentEmail(String name,String toEmali) throws Exception{
		try {
			//todo具体内容可以添加
			String content = String.format("<h1> %s 您好, 恭喜您注册成功</br><h3>填复制下面链接，填写邮箱号，输入密码即可登陆平台下载文件</h3></h1><h3><a herf='http://lpp.glc360.com:8080/'>http://lpp.glc360.com:8080</a></h3>", name);
			mailSender.sendMail("注册成功GLC物流规划与决策系统", content,toEmali);
		} catch (Exception e) {
			e.printStackTrace();
		}

	/*	Properties properties = new Properties();
		properties.put("mail.transport.protocol", "smtp"); // 连接协议
		properties.put("mail.smtp.host", "smtp.qq.com"); // 主机名
		properties.put("mail.smtp.port", 465);  // 端口号
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.ssl.enable", "true");  // 设置是否使用ssl安全连接 (一般都使用)
		properties.put("mail.debug", "true"); // 设置是否显示debug信息 true 会在控制台显示相关信息
		// 得到回话对象
		Session session = Session.getInstance(properties);
		// 获取邮件对象
		javax.mail.Message message = new MimeMessage(session);
		// 设置发件人邮箱地址
		message.setFrom(new InternetAddress("2399029275@qq.com"));
		// 设置收件人地址
		message.setRecipients( javax.mail.Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(toEmali) });
		// 设置邮件标题
		message.setSubject("由JavaMail发出的测试邮件");
		// 设置邮件内容
		message.setContent("<h1>您的注册申请已成功，登陆lpp.glc360.com:8080下载文件:</br><h3>填写邮箱号，输入密码即可登陆平台</h3></h1><h3><a herf='http://lpp.glc360.com:8080/'>http://lpp.glc360.com:8080</a></h3>","text/html;Charset=UTF-8");
		// 得到邮差对象
		Transport transport = session.getTransport();
		// 连接自己的邮箱账户
		transport.connect("2399029275@qq.com", "zmnxuvlfiogudifc"); //密码为刚才得到的授权码
		// 发送邮件
		transport.sendMessage(message, message.getAllRecipients());
		*/

	}
	public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
		// 1. 创建一封邮件
		MimeMessage message = new MimeMessage(session);

		// 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
		message.setFrom(new InternetAddress(sendMail, "glc360环球物流平台", "UTF-8"));

		// 3. To: 收件人（可以增加多个收件人、抄送、密送）
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "用户", "UTF-8"));

		// 4. Subject: 邮件主题（标题有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改标题）
		message.setSubject("GLC注册", "UTF-8");

		// 5. Content: 邮件正文（可以使用html标签）（内容有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改发送内容）
		message.setContent("XX用户你好, 恭喜你注册成功", "text/html;charset=UTF-8");

		// 6. 设置发件时间
		message.setSentDate(new Date());

		// 7. 保存设置
		message.saveChanges();

		return message;
	}



	@ResponseBody
	@Permission("2001")
	@RequestMapping("/{userId}")
	public User getUser(@PathVariable Long userId) {
		return userService.selectById(userId);
	}

	/**
	 * 城市数据导入--客户分析数据--ajax获取数据
	 */
	@ResponseBody
	@RequestMapping("/getData")
	@Permission("1001")
	public String getData(Page<User> page, String batchId) {
		page = new Page<User>(page.getCurrent(), page.getSize());
		EntityWrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.eq("status",2);
		wrapper.orderBy("lastTime", false);
		page = userService.selectPage(page, wrapper);
		return jsonPage(page);
	}


	/**
	 * 设置头像
	 */
	@Permission(action = Action.Skip)
	@RequestMapping(value = "/setAvatar", method = RequestMethod.GET)
	public String setAvatar() {
		return "/user/avatar";
	}
}
